<template>
    <div class="alarmConfiguration zy-content ">
        <search :columns="searchData" @getSearch="getSearch(arguments)"></search>
        <div class="list-layout mt16">
            <div class="btns clear">
                <span class="title">{{ $t('common.listInformation') }}</span>
                <Button v-has="'additionalrecording'" @click="createfaultCodeShowH">补录</Button>
                <Button v-has="'addBatchexport'" @click="exportTemplateClick">{{ $t('common.batchExport') }}</Button>
            </div>
            <div class="tableContent">
                <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList"
                    ellipsis ref="selection" stripe :data="dataArr" @on-selection-change="onSelectChange">
                </Table>
            </div>
            <div class="pageWrap mt16">
                <pageLeftTitle :total="total" :selected="delIds.length" />
                <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
                    @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
            </div>
        </div>
        <!-- 新增编辑 -->
        <Modal :mask-closable="false" v-model="create" :title="addtitle" class="modal-content-layout">
            <Form ref="form" class="formList" :model="formItem" label-position="top" :rules="ruleValidate">
                <FormItem label="功能位置" prop="functionalLocation">
                    <!-- <Select readonly v-model="formItem.functionalLocation" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                        @on-change="getBackupList($event)">
                        <Option v-for="(item) of orgList" :value="item.code" :key="item.code" :label="item.name">
                        </Option>
                    </Select> -->
                     <Cascader disabled :data="orgList" v-model="formItem.functionalLocation" change-on-select placeholder="请选择">
              </Cascader>
                </FormItem>
                <FormItem label="工序" prop="manufacturingProcess">
                    <Input readonly type="text" v-model="formItem.manufacturingProcess"
                        :maxlength="32"></Input>
                </FormItem>
                <FormItem label="设备编号" prop="deviceNo">
                    <Input readonly type="text" v-model="formItem.deviceNo" :placeholder="`${$t('common.inputInfo')}`"
                        :maxlength="32"></Input>
                </FormItem>
                <FormItem label="开始时间" prop="startTime">
                    <Input readonly type="text" v-model="formItem.startTime" :placeholder="`${$t('common.inputInfo')}`"
                        :maxlength="32"></Input>
                </FormItem>
                <FormItem label="结束时间" prop="endTime">
                    <Input readonly type="text" v-model="formItem.endTime" :placeholder="`${$t('common.inputInfo')}`"
                        :maxlength="32"></Input>
                </FormItem>

                <FormItem label="停机类别" prop="shutdownCategoryId">
                    <Select  v-model="formItem.shutdownCategoryId" filterable clearable @on-change='shutdownCategoryChange' :placeholder="`${$t('common.inputInfo')}`">
                        <Option v-for="(item, index) of shutdownList" :value="item.id" :key="index"
                            :label="item.shutdownCategory"></Option>
                    </Select>
                </FormItem>
                <FormItem label="停机原因" prop="periodPropertiesId">
                    <Select @on-change='periodPropertiesChange' v-model="formItem.periodPropertiesId" filterable clearable :placeholder="`${$t('common.inputInfo')}`">
                        <Option v-for="(item, index) of resultList" :value="item.id" :key="index"
                            :label="item.reasonForShutdown"></Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" :loading="loading" @click="addOk('form')">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <importExcelModal :importExcelStateF="importExcelState" v-if="importExcelState"
            @importExcelChange="importExcelChange"></importExcelModal>
    </div>
</template>

<script>
import {  deleteApi, templateApi, exportApi } from "@/api/spareParts/storeHouse.js";
import {  getBackup, findOrgByToken } from "@/api/index.js";
// import importExcelModal from '@/components/importExcel.vue';
import search from "@/components/curd/searchList.vue";
import fileDownload from 'js-file-download';
import toggleTableOperation from "@/mixins/toggleTableOperation";
import recursion from "@/util/recursion";
export default {
    name: "storeHouse",//仓库配置
    components: { search },
    mixins: [toggleTableOperation],
    data() {
        return {
            wareHouseList: [],
            showDetailDialog: false,
            backupList: [],
            shelfList: [],
            locationList: [],
            importExcelState: false, /*批量导入*/
            formItem: {},
            addtitle: "",
            allCheck: false,
            loading: false,
            create: false,
            searchParams: {},
            pageNum: 1,
            pageSize: 10,
            total: 0,

            pageNum2: 1,
            pageSize2: 10,
            total2: 0,
            statusList: [
                {
                    label: "停机",
                    value: 0,
                },
                // {
                //     label: "运行",
                //     value: 1,
                // },
                {
                    label: "待机",
                    value: 3,
                },
            ],
            searchData: [
                {
                    title: "功能位置",
                    key: "functionalLocation",
                    type: "cascader",
                    dicUrl: "/basic/organization/findListByToken?level=0",
                    params: {
                        label: "name",
                        value: "code",
                        children: "children",
                    },
                },
                {
                    title: "工序",
                    key: "manufacturingProcess",
                },
                {
                    title: "设备编号",
                    key: "deviceNo",
                },
                {
                    title: "班次日期",
                    key: "shiftTime",
                    type: "daterange",
                },
                {
                    title: "状态",
                    key: "state",
                    type: "select",
                    dicData:[
                        {
                            label: "停机",
                            value: 0,
                        },
                        {
                            label: "运行",
                            value: 1,
                        },
                        {
                            label: "待机",
                            value: 3,
                        },
                    ],
                    params: {
                        label: "label",
                        value: "value",
                    }
                },
            ],
            columns: [
                {
                    key: 'selection',
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '功能位置',
                    key: 'functionalLocationName',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '工序',
                    key: 'manufacturingProcess',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '设备编号',
                    key: 'deviceNo',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '设备名称',
                    key: 'deviceName',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '停机类别',
                    key: 'shutdownCategory',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '停机原因',
                    key: 'periodProperties',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '班次日期',
                    key: 'shiftTime',
                    minWidth: 130,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '状态',
                    key: 'stateName',
                    minWidth: 130,
                    align: 'center',
                    resizable: true,
                    // render: (h, params) => {
                    //     return h('div', [
                    //         h('span', {}, this.statusList.find(item => item.value === params.row.state).label)
                    //     ])
                    // }
                },
                {
                    title: '班次',
                    key: 'shift',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '开始时间',
                    key: 'startTime',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '结束时间',
                    key: 'endTime',
                    minWidth: 180,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '时长(min)',
                    key: 'duration',
                    minWidth: 180,
                    align: 'center',
                    resizable: true
                },
                {
                    title: '维护人',
                    key: 'operator',
                    minWidth: 180,
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${this.$t('common.CreateTime')}`,
                    key: 'createTime',
                    minWidth: 150,
                    align: 'center',
                    resizable: true
                },
                // {
                //     //title: '操作',
                //     title: `${this.$t('common.operation')}`,
                //     slot: "action",
                //     fixed: 'right',
                //     minWidth: 160,
                //     align: "center"
                // }
            ],
            columns2: [
                // {
                //     key: "selection",
                //     type: "selection",
                //     width: 60,
                //     align: "center",
                // },
                {
                    title: "序号",
                    key: "index",
                    type: "index",
                    width: 100,
                    align: "center",
                },
                {
                    title: "批次属性",
                    key: "deviceName",
                    minWidth: 200,
                    align: "center",
                    resizable: true,
                    tooltip: true,
                },
                {
                    title: "属性内容",
                    key: "assetCode",
                    minWidth: 200,
                    align: "center",
                    resizable: true,
                    tooltip: true,
                },
            ],
            orgList: [],//功能位置
            dataArr: [],
            dataArr2: [],
            resultList:[],
            delFaultCodeShowF: false,//是否显示删除弹窗
            pageSizeOption: [10, 20, 30, 40],
            delIds: [],
            delIds2: [],
            selection: [],
            checkBtnPermission: {},
            shutdownList: [],
            ruleValidate: {
                // manufacturingProcess: [ { required: true, message: '请输入', trigger: 'blur', type: 'string' }],
                periodPropertiesId: [ { required: true, message: '请选择', trigger: 'change', type: 'number' }],
                shutdownCategoryId: [ { required: true, message: '请选择', trigger: 'change', type: 'number' }],
                functionalLocation: [ { required: true, message: '请选择', trigger: 'change', type: 'array' }],
                startTime: [ { required: true, message: '请选择', trigger: 'blur', type: 'string' }],
                endTime: [ { required: true, message: '请选择', trigger: 'blur', type: 'string' }],
                deviceNo: [ { required: true, message: '请选择', trigger: 'blur', type: 'string' }],

            }
        }
    },
    mounted() {
        this.getTableColumnsWidth(this.columns)
        this.searchList();
        // 基础数据，字典数据
        this.getOrgList()
        this.getShutdownList();
        // this.getUserList();
    },
    methods: {
        getSearch( arg ){
            this.searchParams=JSON.parse(JSON.stringify(arg[0]));
            if (this.searchParams.shiftTime && this.searchParams.shiftTime.length > 0) {
                this.searchParams.shiftStartTime = this.searchParams.shiftTime[0];
                this.searchParams.shiftEndTime = this.searchParams.shiftTime[1];
                delete this.searchParams.shiftTime;
            }
            this.pageNum=1;
            this.searchList();
        },
        shutdownCategoryChange(val){
            let res=this.shutdownList.find(item=>item.id==val)
            this.formItem.shutdownCategory=res.shutdownCategory;
            this.getResultList(val);
        },
        periodPropertiesChange(val){
            let res=this.resultList.find(item=>item.id==val)
            this.formItem.periodProperties=res.reasonForShutdown;
            this.formItem.periodPropertiesId=val;
        },
        getResultList(val){
            this.axios({
                url: '/dms/shutdownReason/getShutdownReasonList',
                method: 'get',
                params: {
                    abnormalId:val,
                    pageSize:999,
                    pageNum:1,
                }
            }).then(res => {
                if (res.code == 200) {
                    this.resultList = res.data.records
                }
            })
        },
        showRowDetail(row) {
            this.dataArr2 = {
                ...row
            }
            this.showDetailDialog = true
        },
        getShutdownList() {
            this.axios({
                url:'/dms/shutdownCategory/getShutdownCategoryList',
                method: 'get',
                params: {
                    pageSize:999,
                    pageNum:1,
                },
            }).then(res => {
                if (res.code === 200) {
                     this.shutdownList = res.data.records
                }
            })
        },
        getOrgList() {
            let params = {
                level: 0,
            };
            findOrgByToken(params).then((res) => {
                if (res.code === 200) {
                    const obj = {
                        label: "name",
                        value: "code",
                        children: "children",
                    };
                    this.orgList = recursion.convertTree(res.data, obj);
                } else {
                    this.$Message.warning({
                        content: res.msg,
                        duration: 6,
                        closable: true,
                    });
                }
            });
        },
        //获取仓库
        getBackupList(data) {
            // if(!this.searchParams.companyId){
            //     this.$Message.warning(({ content:"请先选择公司", duration: 6, closable: true }));
            //     return false;
            // }
            let params = {
                companyId: data
            }
            getBackup(params).then(res => {
                if (res.code === 200) {
                    this.backupList = res.data
                }
                // else {
                //     this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                // }
            }).finally(() => {
                this.loading = false
            })
        },
        reset() {
            this.searchParams = {};
            this.changeNum();
        },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },

        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        //查询列表
        searchList() {
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                ...this.searchParams
            };
            this.axios({
                method: 'post',
                url: '/dms/recording/getSupplementaryRecordingList',
                data: params,
            }).then(res => {

                if (res.code === 200) {
                    this.dataArr = res.data.records
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //增加或编辑
        createfaultCodeShowH() {
            if (this.delIds.length!==1) {
                this.$Message.warning('请选择一条数据进行操作')
                return
            }
            this.addtitle = '补录',
            this.$refs.form.resetFields();
            if (this.delIds[0].scode) {
                this.formItem = {
                    ...this.delIds[0],
                }
            }
            this.create = true;
        },
        addOk(name) {
            // if (this.formItem.companyId) {
            //     this.formItem.companyName = this.wareHouseList.map(
            //         (item, index) => {
            //             if (this.formItem.companyId == item.id) {
            //                 return item.name
            //             }
            //         }
            //     )

            //     this.formItem.companyName = this.formItem.companyName[0];
            // }
            this.$refs[name].validate((valid) => {
                if (!valid) {
                    return
                } else {
                    this.loading = true;
                    if (this.formItem.scode) {
                        this.axios({
                            url:'/dms/recording/updateSupplementaryRecording',
                            method: 'post',
                            data: this.formItem
                        }).then(res => {
                            this.loading = false; 0
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success("补录成功");
                                this.create = false;
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    }
                }
            })

        },
        //勾选列表
        onSelectChange(selection) {
            let myArray = [];
            selection.map((item, index) => {
                myArray.push(item);
            });
            this.delIds = myArray;
            if (selection.length > 0) {
                this.allCheck = true;
            } else {
                this.allCheck = false;
            }
        },
        //批量删除
        delFaultCodeShowClick() {
            if (this.delIds.length == 0) {
                this.$Message.warning({
                    content: `${this.$t('common.deleteItems')}`,
                    duration: 6,
                    closable: true,
                });
                return;
            } else {
                this.delFaultCodeShowF = true;
            }
        },
        //删除
        delPrrShowH(row) {
            //点击展示提示删除弹窗
            this.delFaultCodeShowF = true;
            this.delIds = [];
            this.delIds.push(row.id);
        },
        deleteOk() {
            this.loading = true;
            let params = { delIds: this.delIds }
            deleteApi(params).then(res => {
                this.loading = false;
                if (res.code === 200) {
                    this.changeNum();
                    this.$Message.success("删除成功");
                    this.allCheck = false;
                    this.delFaultCodeShowF = false;
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //下载模板
        exportTemplate() {
            const filName = '仓库配置模板'
            templateApi().then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        },
        //导入
        importExcelShow() {
            this.importExcelState = true;
        },
        importExcelChange(val) {
            this.importExcelState = false;
            if (val === 'success') {
                this.changeNum();
            }
        },
        //导出
        exportTemplateClick() {
            let params = {
                delIds: this.delIds,
            };
            for (let key in this.searchParams) {
                if (this.searchParams[key]) {
                    this.$set(params, key, this.searchParams[key])
                }
            }
            const filName = '停机原因'
            exportApi(params).then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        }
    }
}
</script>

<style scoped lang="scss">
.ivu-input-number {
    width: -webkit-fill-available;
}

.row_click {
    cursor: pointer;
    color: rgb(50, 113, 240) !important;
}
</style>

